package org.x.commonmod.config;

import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class GlobalExceptionHandler {

    // 1. 先添加对JSON解析异常的处理
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public Result handleHttpMessageNotReadable(HttpMessageNotReadableException ex) {
        // 优先检查是否有根因异常
        Throwable rootCause = ex.getRootCause();
        if (rootCause != null) {
            return Result.error("请求参数解析失败: " + rootCause.getMessage());
        }

        // 没有根因时使用异常自身的消息
        return Result.error("请求参数不合法: " + ex.getMessage());
    }

    // 2. 保留原有的参数校验处理
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result handleValidation(MethodArgumentNotValidException e) {
        String message = e.getBindingResult().getFieldError().getDefaultMessage();
        return Result.fail("400", message);
    }

    @ExceptionHandler(InsufficientPermissionsException.class)
    public Result handleInsufficientPermissions(InsufficientPermissionsException e) {
        return Result.fail("403", e.getMessage());
    }

    // 3. 最后处理其他异常（放在最后）
    @ExceptionHandler(Exception.class)
    public Result handleException(Exception e) {
        return Result.fail("500", e.getMessage());
    }
}